import {
    request,
    encodeUrl,
    AbstractBookCrawler,
    BasicBook,
    SearchBookResult,
    Book,
    BasicChapter,
    BookCrawlerTest,
    BookSource,
} from "../../common/common_node.js";

class BookCrawler extends AbstractBookCrawler {
    options = {decoder: 'gbk'}

    async searchBook(keyword, pageNum) {
        function getBoolList($) {
            const bookArr = [];
            const bookBoxArr = $(".type_show .bookbox");
            bookBoxArr.each(function (index, elem) {
                let nameAndPath = $(this).find(".bookname a");
                bookArr.push(new BasicBook({
                    name: nameAndPath.html(),
                    author: $(this).find(".author").html().replace("作者：", ""),
                    path: nameAndPath.attr("href"),
                }));
            })
            return bookArr;
        }

        let url = `${this.source.searchBaseUrl}/uixfdhvidufhgidr.php?ie=gbk&q=${encodeUrl(keyword, 'gb2312')}`;
        const doc = await (await request(url, this.options)).doc();
        const bookArr = getBoolList(doc);

        return new SearchBookResult({
            pageNum: 1,
            pages: 1,
            keyword: keyword,
            bookList: bookArr
        });
    }

    async bookDetails(path) {
        const $ = await (await request(this.source.bookBaseUrl + path, this.options)).doc();
        return new Book({
            name: $("meta[property='og:novel:book_name']").attr('content'),
            author: $("meta[property='og:novel:author']").attr('content'),
            path: path,
            intro: $("meta[property='og:description']").attr('content'),
            coverUrl: $("meta[property='og:image']").attr('content'),
            type: $("meta[property='og:novel:category']").attr('content')
        });
    }

    async bookCatalog(path) {
        const $ = await (await request(this.source.bookBaseUrl + path, this.options)).doc();
        let chapters = $('.listmain dl dd a');
        let catalog = [];
        chapters.each(function (i, elem) {
            const item = $(elem);
            catalog.push(new BasicChapter({
                index: i,
                title: item.html(),
                path: item.attr("href")
            }));
        });
        return catalog;
    }

    async chapterContent(path) {
        const $ = await (await request(this.source.bookBaseUrl + path, this.options)).doc();
        return $("#content").text();
    }
}

const source = {
    "id": "free_book_js/3",
    "name": "读书吧中文网",
    "portalUrl": "http://www.zjxs.cc",
    "searchBaseUrl": "http://www.zjxs.cc",
    "bookBaseUrl": "http://www.zjxs.cc",
    "active": true
};

await new BookCrawlerTest(new BookCrawler(BookSource.createTestBookSource(source)), {
    enableSearch: true,
    keyword: "全球高武",
}).run();

//debugger;

